package com.mairuide.phone.import_phone;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mairuide.datalog.*;
import com.mairuide.phone.callanalysis.CallanalysisVo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.base.PageSupport;
import com.mairuide._frame.utils.GsonUtil;
import com.mairuide._frame.utils.MD5;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.entity.PageResult;
import com.mairuide.entity.Result;
import com.mairuide.entity.StatusCode;
import com.mairuide.menuinfo.MenuInfo;
import com.mairuide.phone.PhoneRecord;

/**
 * @Auther: zyj
 * @Date: 2018/12/13 18:06
 * @Description:
 */
@Controller
@RequestMapping("/phone/record")
public class PhoneRecordController extends BaseController {

    @Autowired
    private PhoneRecordingService phoneRecordingService;
    @Resource
    private DataOperationLogService dataOperationLogService;
    @Autowired
    private DataOperationImportLogService dataOperationImportLogService;

    @ModuleCode(pValue = "call", value = "callanalysis")
    @RequestMapping(value = "/status", method = RequestMethod.GET)
    public Object billstatus(ModelMap model, PageSupport pagesupport) {
        model.addAttribute("menu", "callstatus");
        Map<String, List<MenuInfo>> secondLevelMenuMap = (Map<String, List<MenuInfo>>)request.getSession().getAttribute("secondLevelMenuMap");
        List<MenuInfo> firstLevelMenuList = (List<MenuInfo>)request.getSession().getAttribute("firstLevelMenuList");
        for(MenuInfo m : firstLevelMenuList){
            if("话单系统".equals(m.getMenuName())){
                List<MenuInfo> menuInfos = secondLevelMenuMap.get(String.valueOf(m.getMenuId()));
                if(menuInfos!=null&&menuInfos.size()>0){
                    String menuUrl = menuInfos.get(0).getMenuUrl();
                    if(menuUrl!=null&&!"/phone/record/status".equals(menuUrl)){
                        return "redirect:"+menuUrl;
                    }
                }
            }
        }
        return "/callanalysis/detail";
    }
    @RequestMapping(value = "/detailmapdialog", method = RequestMethod.GET)
    public Object detailmapdialog(ModelMap model) {
        return "/phonerecord/callanalysis/detailmapdialog";
    }
    @RequestMapping(value = "/compeopledetailDialog", method = RequestMethod.GET)
    public Object compeopledetailDialog(ModelMap model) {
        return "/phonerecord/callanalysis/compeopledetailDialog";
    }
    @ModuleCode(pValue = "phoneanalysis",value = "phoneimport")
    @RequestMapping(value = "/phoneimport", method = RequestMethod.GET)
    public Object importFile(ModelMap model) {
        return "/phonerecord/importPhone";
    }
    @ModuleCode(pValue = "phoneanalysis",value = "phoneexport")
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public Object exportFile(ModelMap model, PageSupport pagesupport,String number,String casemanageId) {
        return "/phonerecord/exportPhone";
    }

    @ResponseBody
    @RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
    public Result exportFile2(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        PageSupport pagesupport = new PageSupport();
        pagesupport.setPageNumber(page);
        pagesupport.setPageSize(size);
        String uid = searchMap.get("casemanageId")==null?"":searchMap.get("casemanageId").toString();
        Page<PhoneRecord> pageList =  phoneRecordingService.findPhoneInformation((String)searchMap.get("number"),uid,pagesupport.getPage(), super.getLoginUser().getId());

        return  new Result(true, StatusCode.OK,"查询成功",  new PageResult<PhoneRecord>(pageList.getTotalElements(), pageList.getContent()) );
    }

    @RequestMapping(method= RequestMethod.POST,value = "phoneRecordDetail")
    @ResponseBody
    public Object getInStreamAccountCount_detail(CallanalysisVo cv){
        return phoneRecordingService.getPhoneRecordDetail(cv);
    }


    /**
     * 话单导入
     * @param file
     * @throws IOException
     */
    @RequestMapping("/uploadPhoneFile")
    @ResponseBody
    public void uploadFile(@RequestParam("fileUpload") MultipartFile[] files, HttpServletRequest request,
                           HttpServletResponse response,String caseId) {
        Map<String, Object> map = new HashMap<>();
        int number = 0;
        String uuid = null;
        Map<String ,Object> logMap = new LinkedHashMap();
//        List<PhoneRecord> list = new ArrayList<>();
        int a=0,b=0;
        List<DataOperationImportLog> dils = new ArrayList<DataOperationImportLog>();
        try {
            for (int i=0;i<files.length;i++) {
                try {
                    MultipartFile file = files[i];
                    //判断文件类型
                    if (file == null || file.getSize() <= 0) {
                        throw new Exception("上传文件类型错误");
                    }
                    String filename = file.getOriginalFilename().split("\\.")[0];
                    uuid = MD5.md5HashCode(file.getInputStream());
                    DataOperationImportLog dil = new DataOperationImportLog();
                    List<DataOperationImportLog> doi = dataOperationImportLogService.findByDealFlowUuidAndIsDeleteAndTableFlat(uuid,caseId,2);
                    if (null == doi || doi.isEmpty()) {
                    	String result = ExcelUtils.getFileSort(file);
                        if ("excel".equals(result)) {
                            map = phoneRecordingService.importPhoneRecordExcel(file, caseId, super.getLoginUser().getId(),uuid);
                        } else if ("txt".equals(result)) {
                            map = phoneRecordingService.importPhoneRecordTxt(file, caseId, super.getLoginUser().getId(),uuid);
                        } else if ("csv".equals(result)){
                            map = phoneRecordingService.importPhoneRecordCSV(file, caseId, super.getLoginUser().getId(),uuid);
                        }
                        dil.setImportResult("成功");
                    }else {
                    	map.put("errorInfo", filename + "为重复导入账单文件");
						dil.setImportResult("失败");
                    }
                    dil.setFileName(file.getOriginalFilename());
                    dil.setDealFlowUuid(uuid);
                    dil.setSuccessNumber(map.get("successNum")==null?0:Integer.parseInt(map.get("successNum").toString()));
                    if (map.get("successNum")==null||Integer.parseInt(map.get("successNum").toString())==0){
                        a++;//失败
                    }else {
                        b++;//成功
                    }
                    dil.setTableFlat(2);
                    dil.setImportResult("成功");
                    dil.setFileSize(String.valueOf(file.getSize()));
                    dil.setUserId(super.getLoginUser().getId());
                    dil.setCreateTime(new Timestamp(System.currentTimeMillis()));
					dil.setImportDesc(map.get("errorInfo") == null ? "" : map.get("errorInfo").toString());
					dils.add(dil);
                } catch (Exception e) {
                    map.put("successNum",0);
                    e.printStackTrace();
                }
            }
            //添加导入日志
            logMap = dataOperationLogService.save(files.length, dils, super.getLoginUser(), SystemFlag.HD, ModuleFlag.PHONERECORDINPUT, ActionType.INPUT, caseId);
            logMap.put("totalFile",dils.size());
            logMap.put("successFile",b);
            logMap.put("errorFile",a);
            if (map!=null){
                response.getWriter().print(GsonUtil.GsonString(SUCCESS(logMap)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	//同步话单数据到人员信息表中
        	phoneRecordingService.updatePersonInformation(caseId);
            try {
                for (int i=0;i<files.length;i++) {
                    MultipartFile file = files[i];
                    //文件上传
                    super.persistFile(file);
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //导出Excel
    @RequestMapping("/createExcel")
    public String createExcel(HttpServletResponse response,String number,String casemanageId) throws Exception {

        XSSFWorkbook workbook1 = new XSSFWorkbook();
        SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
        //创建HSSFWorkbook对象(excel的文档对象)
//        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        Sheet sheet=wb.createSheet("话单详情表");
        //在sheet里创建第二行
        Row row2=sheet.createRow(0);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("业务类型");
        row2.createCell(1).setCellValue("起始时间");
        row2.createCell(2).setCellValue("服务号码");
        row2.createCell(3).setCellValue("服务号码用户信息");
        row2.createCell(4).setCellValue("服务号码归属地");
        row2.createCell(5).setCellValue("卡号");
        row2.createCell(6).setCellValue("设备号码");
        row2.createCell(7).setCellValue("对方号码");
        row2.createCell(8).setCellValue("对方号码用户信息");
        row2.createCell(9).setCellValue("对方号码归属地");
        row2.createCell(10).setCellValue("通话时长");
        row2.createCell(11).setCellValue("呼叫类型");
        row2.createCell(12).setCellValue("LAC");
        row2.createCell(13).setCellValue("CID");
        row2.createCell(14).setCellValue("服务号码基站");
        row2.createCell(15).setCellValue("MSC");
        row2.createCell(16).setCellValue("城市");
        row2.createCell(17).setCellValue("第三方号码");
        row2.createCell(18).setCellValue("第三方号码用户信息");
        row2.createCell(19).setCellValue("第三方号码归属地");
        row2.createCell(20).setCellValue("漫游城市或运营商代码");
        row2.createCell(21).setCellValue("漫游城市或运营商代码信息");
        row2.createCell(22).setCellValue("业务键");
        //在sheet里创建第三行
        PageRequest pageRequest = new PageRequest(0,Integer.MAX_VALUE);
        Page<PhoneRecord> pageList =  phoneRecordingService.findPhoneInformation(number,casemanageId,pageRequest, super.getLoginUser().getId());
        List<PhoneRecord> recordList = pageList.getContent();

        if (recordList!=null && recordList.size()>0){
            for (int i=0;i<recordList.size();i++){
                PhoneRecord phoneRecord = recordList.get(i);
                Row row3=sheet.createRow(i+1);
                row3.createCell(0).setCellValue(phoneRecord.getBusinessType());
                row3.createCell(1).setCellValue(DateUtils.getDateString(phoneRecord.getStartingTime()));
                row3.createCell(2).setCellValue(phoneRecord.getServiceNumber());
                row3.createCell(3).setCellValue(phoneRecord.getServiceUserInformation());
                row3.createCell(4).setCellValue(phoneRecord.getServiceLocation());
                row3.createCell(5).setCellValue(phoneRecord.getCardNumber());
                row3.createCell(6).setCellValue(phoneRecord.getDeviceNumber());
                row3.createCell(7).setCellValue(phoneRecord.getPartyNumber());
                row3.createCell(8).setCellValue(phoneRecord.getPartyUserInformation());
                row3.createCell(9).setCellValue(phoneRecord.getPartyLocation());
                row3.createCell(10).setCellValue(phoneRecord.getTalkTime());
                row3.createCell(11).setCellValue(phoneRecord.getCallType());
                row3.createCell(12).setCellValue(phoneRecord.getLac());
                row3.createCell(13).setCellValue(phoneRecord.getCid());
                row3.createCell(14).setCellValue(phoneRecord.getBaseStation());
                row3.createCell(15).setCellValue(phoneRecord.getMsc());
                row3.createCell(16).setCellValue(phoneRecord.getCity());
                row3.createCell(17).setCellValue(phoneRecord.getThirdNumber());
                row3.createCell(18).setCellValue(phoneRecord.getThirdNumberInformation());
                row3.createCell(19).setCellValue(phoneRecord.getThirdNumberLocation());
                row3.createCell(20).setCellValue(phoneRecord.getOperationCode());
                row3.createCell(21).setCellValue(phoneRecord.getOperationCodeInformation());
                row3.createCell(22).setCellValue(phoneRecord.getBusinessKey());
            }
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "话单信息" + dateFormat.format(new Date());
        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+ExcelUtils.toUtf8String(fileName+".xlsx"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        //添加导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.PHONERECORDEXPORT, ActionType.EXPORT);
        return null;
    }

}
